package org.jaronsource.framework.core.service;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

import org.jaronsource.framework.core.dao.support.PageRequest;
import org.jaronsource.framework.core.dao.support.Sort;
import org.jaronsource.framework.util.StringUtils;

public class SearchForm implements Serializable, Cloneable {

	private static final long serialVersionUID = 1L;

	public static final String OP_LIKE_SUFFIX = "_lk";
	public static final String OP_BOTH_LIKE_SUFFIX = "_blk";
	public static final String OP_NOT_LIKE_SUFFIX = "_nlk";
	public static final String OP_NOT_BOTH_LIKE_SUFFIX = "_nblk";
	public static final String OP_EQ_SUFFIX = "_eq";
	public static final String OP_NOT_EQ_SUFFIX = "_neq";
	public static final String OP_GT_SUFFIX = "_gt";
	public static final String OP_LT_SUFFIX = "_lt";
	public static final String OP_EQ_AND_GT_SUFFIX = "_egt";
	public static final String OP_EQ_AND_LT_SUFFIX = "_elt";
	public static final String OP_IN_SUFFIX = "_in";

	public static final String TYPE_STRING = "_string";
	public static final String TYPE_INT = "_int";
	public static final String TYPE_FLOAT = "_float";
	public static final String TYPE_SPLITTXT = "_split";
	public static final String TYPE_SPLIT_INT = "_splitint";
	public static final String TYPE_SPLIT_FLOAT = "_splitfloat";

	public static final String TYPE_DEFAULT = TYPE_STRING;

	private Map<String, String> form = new HashMap<String, String>();

	private String order;
	
	private PageRequest pageRequest = new PageRequest();

	public Map<String, String> getForm() {
		return form;
	}

	public void setForm( Map<String, String> form ) {
		this.form = form;
	}

	public void setPageRequest( PageRequest pageRequest ) {
		this.pageRequest = pageRequest;
	}

	public void setPageNo( int pageNo ) {
		this.pageRequest.setPageNo( pageNo );
	}

	public void setPageSize( int pageSize ) {
		this.pageRequest.setPageSize( pageSize );
	}

	public String getOrder() {
		return order;
	}

	public void setOrder( String order ) {
		this.order = order;
	}

	public SearchForm addFormEntry( String key, String value ) {
		form.put( key, value );
		return this;
	}

	public PageRequest getPageRequest() {

		if ( !StringUtils.isBlank( order ) ) {
			if ( !StringUtils.isBlank( order ) && order.indexOf( "_" ) != -1 ) {
				String[] tmp = StringUtils.split( order, "_" );
				String[] orderBys = StringUtils.split(tmp[0], ","); 
				String[] orders = StringUtils.split(tmp[1], ",");
				Sort sort = new Sort();
				
				for (int i = 0; i < orderBys.length; i++) {
					sort.order(orderBys[i], orders[i]);
				}
				
				pageRequest.setSort( sort );
			}
		}

		return pageRequest;
	}
}